import {
	setStorage,
	getStorage,
	removeStorage
} from "@/util/auth";
import {
	login as loginApi,
	getUserInfo
} from "@/api/user.js";
import Vue from "vue";
const state = {
	token: getStorage('token'),
	user: getStorage('user'),
}
const mutations = {
	SET_TOKEN(state, token) {
		if (token === null) {
			removeStorage('token');
		} else {
			setStorage('token', token, 259200)
		}
		state.token = token;
	},
	SET_USER(state, user) {
		if (user === null) {
			removeStorage('user');
		} else {
			setStorage('user', user, 259200)
		}
		state.user = user
		uni.$emit('updateUser', user);
	},
}
const actions = {
	getWxLoginCode({
		commit
	}, code) {
		return new Promise((resolve, reject) => {
			loginApi({
				code
			}).then((res) => {
				commit('SET_TOKEN', res.token);
				if (res.userList) {
					commit('SET_USER', res.userList[0]);
				}
				resolve();
			}).catch(() => {
				reject();
			})
		})
	},
	getUser({
		commit
	}) {
		return new Promise((resolve, reject) => {
			getUserInfo().then((res) => {
				commit('SET_USER', res);
				resolve();
			}).catch(() => {
				reject();
			})
		})
	}
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}